import { game, ui, _status, ai, lib, get } from "../../../noname.js";
//import { initBegin, initPlayers, chooseSkill, chooseAvatar, chooseGroup, addCharacterUse } from "./chooseSkill.js"
import { swTool } from "../main/swTool.js";

export const identity = {
    chooseMode() {//初始化游戏完成，分配选将逻辑
        const mode = _status.mode.slice(0, 1).toUpperCase() + _status.mode.slice(1);//首字母大写
        if (typeof game['chooseCharacter' + mode + 'OL'] === 'function') {//存在对应的选择角色逻辑就跳转
            game['chooseCharacter' + mode + 'OL']()
            return;
		}
		//反之用默认的
        const next = game.createEvent('chooseCharacter');
        next.set('mode', mode)
		next.setContent(function () {
			"step 0"
			game.broadcastAll(() => { ui.arena.classList.add('choose-character') })
			var i;
			var identityList;
			if (_status.mode == 'zhong') {
				event.zhongmode = true;
				identityList = ['zhu', 'zhong', 'mingzhong', 'nei', 'fan', 'fan', 'fan', 'fan'];
			} else {
				identityList = get.identityList(game.players.length);
				if (lib.configOL.double_nei) {
					switch (lib.configOL.number) {
						case 8:
							identityList.remove('fan');
							identityList.push('nei');
							break;
						case 7:
							identityList.remove('zhong');
							identityList.push('nei');
							break;
						case 6:
							identityList.remove('fan');
							identityList.push('nei');
							break;
						case 5:
							identityList.remove('fan');
							identityList.push('nei');
							break;
						case 4:
							identityList.remove('zhong');
							identityList.push('nei');
							break;
						case 3:
							identityList.remove('fan');
							identityList.push('nei');
							break;
					}
				}
			}
			identityList.randomSort();

			for (i = 0; i < game.players.length; i++) {
				game.players[i].identity = identityList[i];
				game.players[i].setIdentity('cai');
				game.players[i].node.identity.classList.add('guessing');
				if (event.zhongmode) {
					if (identityList[i] == 'mingzhong') {
						game.zhu = game.players[i];
					} else if (identityList[i] == 'zhu') {
						game.zhu2 = game.players[i];
					}
				} else {
					if (identityList[i] == 'zhu') {
						game.zhu = game.players[i];
					}
				}
				game.players[i].identityShown = false;
			}
			if (lib.configOL.special_identity && !event.zhongmode && game.players.length == 8) {
				var map = {};
				var zhongs = game.filterPlayer(function (current) {
					return current.identity == 'zhong';
				});
				var fans = game.filterPlayer(function (current) {
					return current.identity == 'fan';
				});
				if (fans.length >= 1) {
					map.identity_zeishou = fans.randomRemove();
				}
				if (zhongs.length > 1) {
					map.identity_dajiang = zhongs.randomRemove();
					map.identity_junshi = zhongs.randomRemove();
				}
				else if (zhongs.length == 1) {
					if (Math.random() < 0.5) {
						map.identity_dajiang = zhongs.randomRemove();
					}
					else {
						map.identity_junshi = zhongs.randomRemove();
					}
				}
				game.broadcastAll(function (zhu, map) {
					for (var i in map) {
						map[i].special_identity = i;
					}
				}, game.zhu, map);
				event.special_identity = map;
			}

			game.zhu.setIdentity();
			game.zhu.identityShown = true;
			game.zhu.isZhu = (game.zhu.identity == 'zhu');
			game.zhu.node.identity.classList.remove('guessing');
			game.me.setIdentity();
			game.me.node.identity.classList.remove('guessing');
			if (game.me.special_identity) {
				game.me.node.identity.firstChild.innerHTML = get.translation(game.me.special_identity + '_bg');
			}

			for (var i = 0; i < game.players.length; i++) {
				game.players[i].send(function (zhu, zhuid, me, identity) {
					for (var i in lib.playerOL) {
						lib.playerOL[i].setIdentity('cai');
						lib.playerOL[i].node.identity.classList.add('guessing');
					}
					zhu.identityShown = true;
					zhu.identity = zhuid;
					if (zhuid == 'zhu') zhu.isZhu = true;
					zhu.setIdentity();
					zhu.node.identity.classList.remove('guessing');
					me.setIdentity(identity);
					me.node.identity.classList.remove('guessing');
					if (me.special_identity) {
						me.node.identity.firstChild.innerHTML = get.translation(me.special_identity + '_bg');
					}
					ui.arena.classList.add('choose-character');
				}, game.zhu, game.zhu.identity, game.players[i], game.players[i].identity);
			}

			var list;
			var list2 = [];
			var list3 = [];
			var list4 = [];
			event.list = [];
			event.list2 = [];

			var libCharacter = {};
			for (var i = 0; i < lib.configOL.characterPack.length; i++) {
				var pack = lib.characterPack[lib.configOL.characterPack[i]];
				for (var j in pack) {
					//if (j == 'zuoci') continue;
					if (lib.character[j]) libCharacter[j] = pack[j];
				}
			}
			for (i in lib.characterReplace) {
				var ix = lib.characterReplace[i];
				for (var j = 0; j < ix.length; j++) {
					if (!libCharacter[ix[j]] || lib.filter.characterDisabled(ix[j])) ix.splice(j--, 1);
				}
				if (ix.length) {
					event.list.push(i);
					event.list2.push(i);
					list4.addArray(ix);
					var bool = false;
					for (var j of ix) {
						if (libCharacter[j][4] && libCharacter[j][4].includes('zhu')) {
							bool = true; break;
						}
					}
					(bool ? list2 : list3).push(i);
				}
			}
			game.broadcast(function (list) {
				for (var i in lib.characterReplace) {
					var ix = lib.characterReplace[i];
					for (var j = 0; j < ix.length; j++) {
						if (!list.includes(ix[j])) ix.splice(j--, 1);
					}
				}
				_status.characterlist = list
			}, list4);
			for (i in libCharacter) {
				if (list4.includes(i)) continue;
				if (lib.filter.characterDisabled(i, libCharacter)) continue;
				event.list.push(i);
				event.list2.push(i);
				list4.push(i);
				if (libCharacter[i][4] && libCharacter[i][4].includes('zhu')) {
					list2.push(i);
				}
				else {
					list3.push(i);
				}
			}
			_status.characterlist = list4.slice(0);

			event.useTime = lib.configOL.choose_timeout
			event.chooseTime = lib.configOL.chooseCharacter_moreTime
			game.broadcastAll((num) => {
				lib.configOL.choose_timeout = Number(num)
			}, event.chooseTime)
			
			//自由点将开始1
			if (lib.configOL.identity_listNum == 'dianjiang') {
				game.broadcastAll(function (list, id, zhu) {
					_status.characterlist = list;
					if (game.me == zhu) {
						var dialog = ui.create.characterDialog('heightset').open()
						dialog.id = id
					}
				}, _status.characterlist, event.videoId, game.zhu);

				game.zhu.chooseButton(true)
					.set('selectButton', (lib.configOL.double_character ? 2 : 1)).set('dialog', event.videoId)
			}
			//自由点将结束1
			else {
				if (lib.configOL.identity_listNum == 'normal') {
					let finalNum = lib.configOL.choice_zhu;
					if (lib.configOL.unbalanced_mode) finalNum = 12;
					var getZhuList = function (list2) {
						var limit_zhu = lib.configOL.limit_zhu;
						if (!limit_zhu || limit_zhu == 'off') return list2.slice(0).sort(lib.sort.character);
						if (limit_zhu != 'group') {
							var num = (parseInt(limit_zhu) || 6);
							return list2.randomGets(num).sort(lib.sort.character);
						}
						var getGroup = function (name) {
							if (lib.characterReplace[name]) return lib.character[lib.characterReplace[name][0]][1];
							return lib.character[name][1];
						}
						var list2x = list2.slice(0);
						list2x.randomSort();
						for (var i = 0; i < list2x.length; i++) {
							for (var j = i + 1; j < list2x.length; j++) {
								if (getGroup(list2x[i]) == getGroup(list2x[j])) {
									list2x.splice(j--, 1);
								}
							}
						}
						list2x.sort(lib.sort.character);
						return list2x;
					}
					list = getZhuList(list2).concat(list3.randomGets(finalNum));
				}
				else {
					let finalNum = swTool.getSelect() || 6
					if (lib.configOL.unbalanced_mode) finalNum = 12;
					var getZhuList = function (list2) {
						var limit_zhu = lib.configOL.limit_zhu;
						if (!limit_zhu || limit_zhu == 'off') return list2.slice(0).sort(lib.sort.character);
						if (limit_zhu != 'group') {
							var num = (parseInt(limit_zhu) || 6);
							return list2.randomGets(num).sort(lib.sort.character);
						}
						var getGroup = function (name) {
							if (lib.characterReplace[name]) return lib.character[lib.characterReplace[name][0]][1];
							return lib.character[name][1];
						}
						var list2x = list2.slice(0);
						list2x.randomSort();
						for (var i = 0; i < list2x.length; i++) {
							for (var j = i + 1; j < list2x.length; j++) {
								if (getGroup(list2x[i]) == getGroup(list2x[j])) {
									list2x.splice(j--, 1);
								}
							}
						}
						list2x.sort(lib.sort.character);
						return list2x;
					}
					list = getZhuList(list2).concat(list3.randomGets(finalNum));
				}
				if (event.zhongmode) {
					list = event.list.randomGets(8);
				}
				var next = game.zhu.chooseButton(true);
				next.set('selectButton', (lib.configOL.double_character ? 2 : 1));
				next.set('createDialog', ['选择角色', [list, 'characterx']]);
				next.set('ai', function (button) {
					return Math.random();
				});
			}
			
			"step 1"
			//自由点将开始2
			if (!result.links || result.links?.length == 0) {
				result.links = _status.characterlist.randomGets(lib.configOL.double_character ? 2 : 1)
			}
			if (lib.configOL.identity_listNum == 'dianjiang') {
				if (game.zhu.isOnline()) {
					game.zhu.send("closeDialog", event.id)
				}
				else if (game.zhu == game.me) {
					var dialog = get.idDialog(event.id);
					if (dialog) {
						dialog.close();
					}
				}
			}
			//自由点将结束2
			if (!game.zhu.name) {
				game.zhu.init(result.links[0], result.links[1])
			}
			event.list.remove(get.sourceCharacter(game.zhu.name1));
			event.list.remove(get.sourceCharacter(game.zhu.name2));
			event.list2.remove(get.sourceCharacter(game.zhu.name1));
			event.list2.remove(get.sourceCharacter(game.zhu.name2));

			if (game.players.length > 4) {
				if (!game.zhu.isInitFilter('noZhuHp')) {
					game.zhu.maxHp++;
					game.zhu.hp++;
					game.zhu.update();
				}
			}
			game.broadcast(function (zhu, name, name2, addMaxHp) {
				if (!zhu.name) {
					zhu.init(name, name2);
				}
				if (addMaxHp && !zhu.isInitFilter("noZhuHp")) {
					zhu.maxHp++;
					zhu.hp++;
					zhu.update();
				}
			}, game.zhu, result.links[0], result.links[1], game.players.length > 4);

			if (game.zhu.group == 'shen' || game.zhu.group == "western" && !game.zhu.isUnseen(0)) {
				game.zhu._groupChosen = "kami";
				var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key', 'shen'];
				for (var i = 0; i < list.length; i++) {
					if (!lib.group.includes(list[i])) list.splice(i--, 1);
					else list[i] = ['', '', 'group_' + list[i]];
				}
				game.zhu.chooseButton(['请选择你的势力', [list, 'vcard']], true).set('ai', function () {
					return Math.random();
				});
			}
			else if (get.is.double(game.zhu.name1)) {
				game.zhu._groupChosen = true;
				var list = get.is.double(game.zhu.name1, true);
				for (var i = 0; i < list.length; i++) {
					if (!lib.group.includes(list[i])) list.splice(i--, 1);
					else list[i] = ['', '', 'group_' + list[i]];
				}
				game.zhu.chooseButton(['请选择你的势力', [list, 'vcard']], true).set('ai', function () {
					return Math.random();
				});
			}
			else event.goto(3);
			"step 2"
			var name = result.links[0][2].slice(6);
			game.zhu.changeGroup(name);
			"step 3"
			var list = [];
			var selectButton = (lib.configOL.double_character ? 2 : 1);
			var num = Math.floor(event.list.length / (game.players.length - 1));
			//自由点将开始3
			if (lib.configOL.identity_listNum == 'dianjiang') {
				game.broadcastAll(function (id, zhu) {
					if (game.me != zhu) {
						var dialog = ui.create.characterDialog('heightset').open()
						dialog.id = id
					}
				}, event.videoId, game.zhu);
			}
			//自由点将结束3
			for (let i = 0; i < game.players.length; i++) {
				swTool.onlineSelectNum = swTool.getSelect()
				if (game.players[i] != game.zhu) {
					//自由点将开始4
					if (lib.configOL.identity_listNum == 'dianjiang') {
						list.push([game.players[i],
							event.videoId, selectButton, true
						]);
					}//自由点将结束4
					else {
						const identity = game.players[i].identity;
						let num2;
						if (event.zhongmode) {
							if (identity == "nei" || identity == "zhu") num2 = 8;
							else num2 = 6;
						} else {
							num2 = lib.configOL["choice_" + identity];
						}
						let str = "选择角色";
						if (game.players[i].special_identity) {
							str += "（" + get.translation(game.players[i].special_identity) + "）";
						}
						if (lib.configOL.identity_listNum != 'normal' && swTool.onlineSelectNum) {
							list.push([game.players[i],
							[str, [event.list.randomRemove(swTool.onlineSelectNum), 'characterx']], selectButton, true
							]);
						} else {
							//TODO:此处要因身份而异
							list.push([game.players[i],
							[str, [event.list.randomRemove(num2), 'characterx']], selectButton, true
							]);
						}
					}
				}
			}
			game.me.chooseButtonOL(list, function (player, result) {
				if (game.online || player == game.me) player.init(result.links[0], result.links[1]);
			}).set("switchToAuto", function () {
				_status.event.result = "ai";
			})
			.set("processAI", function () {
				return "ai";
			});


			"step 4"
			game.broadcastAll((num) => {
				lib.configOL.choose_timeout = Number(num)
			}, event.useTime)
			//自由点将开始5
			if (lib.configOL.identity_listNum == 'dianjiang') game.broadcastAll("closeDialog", event.id)
			//自由点将结束5
			var shen = [];
			for (var i in result) {
				if (result[i] && result[i].links) {
					for (var j = 0; j < result[i].links.length; j++) {
						event.list2.remove(get.sourceCharacter(result[i].links[j]));
					}
				}
			}
			
			for (var i in result) {
				if (result[i] == 'ai') {
					result[i] = event.list2.randomRemove(lib.configOL.double_character ? 2 : 1);
					for (var j = 0; j < result[i].length; j++) {
						var listx = lib.characterReplace[result[i][j]];
						if (listx && listx.length) result[i][j] = listx.randomGet();
					}
				}
				else {
					result[i] = result[i].links;
				}
				if (get.is.double(result[i][0]) || (lib.character[result[i][0]] && (lib.character[result[i][0]].group == "shen" || lib.character[result[i][0]].group == "western") && !lib.character[result[i][0]].hasHiddenSkill)) shen.push(lib.playerOL[i]);
			}
			event.result2 = result;
			if (shen.length) {
				var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key'];
				for (var i = 0; i < list.length; i++) {
					if (!lib.group.includes(list[i])) list.splice(i--, 1);
					else list[i] = ['', '', 'group_' + list[i]];
				}
				for (var i = 0; i < shen.length; i++) {
					if (get.is.double(result[shen[i].playerid][0])) {
						shen[i]._groupChosen = "double";
						shen[i] = [
							shen[i],
							[
								"请选择你的势力",
								[
									get.is.double(result[shen[i].playerid][0], true).map(function (i) {
										return ["", "", "group_" + i];
									}),
									"vcard",
								],
							],
							1,
							true,
						];
					} else {
						shen[i]._groupChosen = "kami";
						shen[i] = [shen[i], ["请选择你的势力", [list, "vcard"]], 1, true];
					}
				}
				game.me.chooseButtonOL(shen, function (player, result) {
					if (player == game.me) player.changeGroup(result.links[0][2].slice(6), false, false);
				}).set('switchToAuto', function () {
					_status.event.result = 'ai';
				}).set('processAI', function () {
					return {
						bool: true,
						links: [_status.event.dialog.buttons.randomGet().link],
					}
				});
			}
			else event._result = {};
			"step 5"
			if (!result) result = {};
			for (var i in result) {
				if (result[i] && result[i].links) result[i] = result[i].links[0][2].slice(6);
				else if (result[i] == 'ai') result[i] = function () {
					var player = lib.playerOL[i];
					var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key'];
					for (var ix = 0; ix < list.length; ix++) {
						if (!lib.group.includes(list[ix])) list.splice(ix--, 1);
					}
					if (_status.mode != 'zhong' && game.zhu && game.zhu.group) {
						if (['re_zhangjiao', 'liubei', 're_liubei', 'caocao', 're_caocao', 'sunquan', 're_sunquan', 'zhangjiao', 'sp_zhangjiao', 'caopi', 're_caopi', 'liuchen', 'caorui', 'sunliang', 'sunxiu', 'sunce', 're_sunben', 'ol_liushan', 're_liushan', 'key_akane', 'dongzhuo', 're_dongzhuo', 'ol_dongzhuo', 'jin_simashi', 'caomao'].includes(game.zhu.name)) return game.zhu.group;
						if (game.zhu.name == 'yl_yuanshu') {
							if (player.identity == 'zhong') list.remove('qun');
							else return 'qun';
						}
						if (['sunhao', 'xin_yuanshao', 're_yuanshao', 're_sunce', 'ol_yuanshao', 'yuanshu', 'jin_simazhao', 'liubian'].includes(game.zhu.name)) {
							if (player.identity != 'zhong') list.remove(game.zhu.group);
							else return game.zhu.group;
						}
					}
					return list.randomGet();
				}();
			}
			var result2 = event.result2;
			game.broadcast(function (result, result2) {
				for (var i in result) {
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i][0], result[i][1]);
					}
					if (result2[i] && result2[i].length) lib.playerOL[i].changeGroup(result2[i], false, false);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			}, result2, result);

			for (var i in result2) {
				if (!lib.playerOL[i].name) {
					lib.playerOL[i].init(result2[i][0], result2[i][1]);
				}
				if (result[i] && result[i].length) lib.playerOL[i].changeGroup(result[i], false, false);
			}

			if (event.special_identity) {
				for (var i in event.special_identity) {
					game.zhu.addSkill(i);
				}
			}
			for (var i = 0; i < game.players.length; i++) {
				_status.characterlist.remove(game.players[i].name);
				_status.characterlist.remove(game.players[i].name1);
				_status.characterlist.remove(game.players[i].name2);
			}
			setTimeout(function () {
				ui.arena.classList.remove('choose-character');
			}, 500);
		});
        return next
    },
    modeConfig() {
		game.chooseCharacterFreeChoiceSkillOL = function () {
			_status.videoInited = true

			game.broadcast((vcardx,a,b) => {
				ui.create.buttonPresets.vcardx = vcardx
				lib.element.player.chooseItem = a
				lib.element.content.chooseItem = b
			}, ui.create.buttonPresets.vcardx, lib.element.player.chooseItem, lib.element.content.chooseItem)
			lib.skillReplace = {}
			const initPlayers = game.players.map(p => {
				if (p.ws || p === game.me) {
					let avatar
					let nickname
					if (p === game.me) {
						avatar = lib.config.connect_avatar
						nickname = lib.config.connect_nickname
					} else {
						avatar = p.ws.avatar
						nickname = p.nickname
					}
					game.addVideo('initAvatar', null, { avatar, nickname, playerid: p.playerid })
					return [p.playerid, avatar, nickname]
				}
			}).filter(Boolean)
			game.broadcastAll((players) => {
				players = players.map(p => [lib.playerOL[p[0]], p[1], p[2]])
				ui.arena.classList.add('choose-character');
				players.forEach(([player, avatar, name]) => {
					name = name.replace('※', '')
					const id = name + player.playerid
					swTool.copyCharacter({
						character: avatar,
						hp: 4,
						skills: [],
						name: id,
						translate: name
					})
					player.init(id)
					player.update()
				})
			}, initPlayers)
			_status.characterListSelect = Object.keys(swTool.initList(() => { }));

			const next = game.createEvent('chooseCharacter')
			next.setContent(async (event) => {
				// const cards = swTool.getCardPileSkills().filter(c=>c+"_skill" in lib.skill&&lib.skill[c+"_skill"].equipSkill)
				const characterList = _status.characterListSelect
				lib.playerSkillOL = {}
				lib.playerCharacterOL = {}
				_status.playerCharacters = {}
				_status.style = { innerHTML: swTool.playerInnerHTML }
				let identityList = get.identityList(game.players.length);
				identityList = identityList.randomSort()
				game.zhu = game.players.randomGet()
				swTool.setPlayersSeat(game.zhu)
				identityList = identityList.remove('zhu')//.remove('nei')
				// identityList.push('zhong')
				const anothplayers = game.players.filter(p => p != game.zhu)
				anothplayers.forEach((p, i) => {
					game.broadcastAll((p, id) => {
						const me = p === game.me
						p.setIdentity(me ? id : 'cai')
						p.node.identity.classList.add(me ? id : 'guessing')
						p.identity = id
					}, p, identityList[i])
				})
				game.broadcastAll((list, innerHTML) => {
					const style = document.createElement('style')
					style.innerHTML = innerHTML
					document.head.appendChild(style)
					game.players.forEach((p, i) => {
						p.node.rightskillList = ui.create.div('.playerskillList', p)
						if (!p.nickname) {//||(p.ws&&!p.isOnline2())
							lib.character[list[i]][3] = []
							lib.character[list[i]][2] = 4
							p.init(list[i])
						}
					})
					game.me.update()
				}, characterList.randomGets(10), _status.style.innerHTML)

				game.addVideo('init', null, game.players.map(p => {
					return {
						name: p.name1,
						name2: p.name2,
						identity: (p === game.me || p === game.zhu) ? p.identity : 'cai'
					}
				}))
				let num = swTool.getSelect()
				_status.characterlist = characterList.slice()
				const map = {}

				_status.skillMap = {}
				const skillList = []
				_status.zhuSkills = {}
				swTool.getSkillMapOfCharacter(characterList, (skill, name) => {
					const translate = lib.translate[skill]
					if(lib.configOL?.identity_banSkill?.includes(skill) || lib.configOL?.identity_banSkill?.includes(translate)) return
					if (!lib.skillReplace[translate]) {
						lib.skillReplace[translate] = []
						skillList.push({ skill, name })
					}
					const group = lib.character[name].group
					const theSkill = lib.skill[skill]
					if (theSkill && theSkill.zhuSkill) {
						if (group in _status.zhuSkills) {
							_status.zhuSkills[group].push(skill)
						} else {
							_status.zhuSkills[group] = []
						}
					}
					if (!theSkill.zhuSkill) {
						lib.skillReplace[translate].add(skill)
					}
					_status.skillMap[skill] = name
				})
				game.broadcast((translates) => {
					lib.skillReplace = translates
				}, lib.skillReplace)

				game.broadcastAll((map) => {
					_status.skillMap = map
					for (const m in map) {
						lib.card[m] = {
							fullimage: true,
							image: 'character:' + map[m]
						}
					}
				}, _status.skillMap)
				debugger
				// cards.forEach(c=>{
				//     const info = lib.skill[c+"_skill"]
				//     if(!info) return;
				//     skillList.push({ skill: c+"_skill", name: c })
				//     skillList2.push(c+"_skill")
				// })
				game.players.forEach(p => {
					if (!lib.playerCharacterOL[p.playerid]) {
						lib.playerCharacterOL[p.playerid] = []
					}
					if (p.identity === 'nei') {
						num += Math.floor(num * 0.3)
					}
					let skills = skillList.randomRemove(num)
					if (!map[p.playerid]) map[p.playerid] = {}
					skills.forEach(({ skill, name }) => {
						map[p.playerid][skill] = name
						if (skill.includes("_skill")) return
						lib.playerCharacterOL[p.playerid].add(name)
					})
				})
				game.broadcastAll((target) => {
					target.setIdentity('zhu')
					target.identity = 'zhu'
					target.showIdentity();
					target.isZhu = true;
					target.seatNum = 1
					target.identityShown = true;
					game.zhu = target
				}, game.zhu)
				ui.arena.classList.add('choose-character');
				event.videoId = lib.status.videoId++;
				event.chooseTime = lib.configOL.choose_timeout
				const choiceNum = parseInt(lib.configOL.identity_freeChoiceSkillNum)
				game.broadcastAll((map, id, time, choiceNum) => {
					lib.configOL.choose_timeout = time
					if (game.me !== game.zhu) {
						const list = Object.keys(map[game.me.playerid])
						const dialog = ui.create.dialog(`请等待主公选将<br>你的技能框↓<br>注意看武将旁边的技能而不是武将原画`, [list, 'vcardx'])
						dialog.videoId = id;
						dialog.classList.add('chooseSkills')
					}
				}, map, event.videoId, parseInt(lib.configOL.chooseCharacter_moreTime), choiceNum);
				game.addVideo('characterMap', null, {
					playerMap: map,
					map: _status.skillMap,
					replace: lib.skillReplace,
					ids: game.players.map(p => p.playerid),
					id: event.videoId,
					nicknames: game.players.map(p => p.nickname)
				})

				if (event.target != game.me || !event.target.isOnline()) await game.delay(2);

				// var next = game.zhu.chooseButton(true).set('ai', Math.random)
				// next.set('selectButton', parseInt(lib.configOL.identity_freeChoiceSkillNum));
				// var result = await next.forResult()

				var next = game.zhu.chooseItem("本局你是主公，请先选择技能");
				next.set("list", [[`你可以从下方的技能列表中挑选 ${choiceNum} 个作为自己的武将牌技能<br>将技能拖动到或点击到右侧的框表示选择`, [Object.keys(map[game.zhu.playerid]), 'vcardx']], ["已选技能"]]);
				next.set("chooseNum", choiceNum);
				next.set("forced", true);
				next.set("filterMove", function (from, to, moved) {
					if (moved[0].includes(from.link)) {
						if (typeof to == "number") {
							if (to == 1) {
								if (moved[1].length >= _status.event.chooseNum) return false;
							}
							return true;
						}
					}
					return true;
				});
				next.set("filterOk", function (moved) {
					return moved[1].length == _status.event.chooseNum;
				});
				var result = await next.forResult()

				let skills;
				if (!result || result == "ai" || !result.moved || result.moved.length < 2) {
					skills = Object.keys(map[game.zhu.playerid]).randomGets(choiceNum);
				}
				else {
					skills = result.moved[1].map(s => s[2])
				}

				const anothPlayer = game.players.filter(p => p !== game.zhu)

				game.broadcastAll((target, players, skills) => {
					game.zhu.addSkill(skills)
					lib.character[game.zhu.name].skills = skills
					let str = ''
					skills.forEach(s => str += get.translation(s) + ' ')
					target.node.rightskillList.innerHTML = str

					game.players.forEach(p => {
						const { x } = p.getBoundingClientRect()
						if (ui.window.clientWidth - x < 200) {
							p.classList.add('rightPlayer')
						} else if (x > 0 && x < 400) {
							p.classList.add('leftPlayer')
						}
					})
				}, game.zhu, anothPlayer, skills.slice(0, Math.max(skills.length - parseInt(lib.configOL.identity_zhuSkillHidePercent), 0)))

				lib.playerSkillOL[game.zhu.playerid] = skills
				game.addVideo('initSkill', game.zhu, { skills, zhu: true })
				game.broadcastAll('closeDialog', event.videoId)
				// game.broadcastAll(() => {
				// 	const dialog = ui.arena.querySelector('.dialog.scroll1.scroll2')
				// 	if (dialog) dialog.remove()
				// })
				const selectSkillList = [];

				for (let i = 0; i < anothPlayer.length; i++) {
					const player = anothPlayer[i]
					const skillList = Object.keys(map[player.playerid])
					selectSkillList.push([player, [`你可以从下方的技能列表中挑选 ${choiceNum} 个作为自己的武将牌技能<br>将技能拖动到或点击到右侧的框表示选择`, [skillList, 'vcardx']], choiceNum, true]);
				}
				//var result = await game.me.chooseButtonOL(selectSkillList).forResult();
				const send = (current, list) => {
					var next = current.chooseItem("选择技能");
					next.set("list", [list.shift(), ["已选技能"]]);
					next.set("chooseNum", list.shift());
					next.set("forced", list.shift());
					next.set("filterMove", function (from, to, moved) {
						if (moved[0].includes(from.link)) {
							if (typeof to == "number") {
								if (to == 1) {
									if (moved[1].length >= _status.event.chooseNum) return false;
								}
								return true;
							}
						}
						return true;
					});
					next.set("filterOk", function (moved) {
						return moved[1].length == _status.event.chooseNum;
					});
					if (game.online) game.resume();
					return next;
				}
				const solve = function (resolve, reject) {
					return function (result, player) {
						if (!result || !result.moved) {
							result = "ai";
						}
						resolve({ [player.playerid]: result });
					};
				};
				var result = await Promise.allSettled(
					selectSkillList.map(st => {
						const current = st.shift();
						const listSend = st;
						return new Promise(async (resolve, reject) => {
							if (current.isOnline()) {
								current.wait(solve(resolve, reject));
								current.send(send, current, listSend);
							}
							else if (current === game.me){
								if (_status.connectMode) game.me.wait(solve(resolve, reject));
								const result = await send(current, listSend).forResult();
								if (_status.connectMode) game.me.unwait(result, current);
								else solve(resolve, reject);
							}
							else {
								const result = await send(current, listSend).forResult();
								resolve({ [current.playerid]: result });
							}
						});
					})
				).catch(() => {});

				result = result
					.filter(r => r.status === 'fulfilled')
					.map(r => r.value)
					.reduce((acc, cur) => ({ ...acc, ...cur }), {});

				for (const r in result) {
					const player = lib.playerOL[r]
					let skills
					if (!result[r] || result[r] == "ai" || !result[r].moved || result[r].moved.length < 2) {
						skills = Object.keys(map[r]).randomGets(choiceNum);
					}
					else {
						skills = result[r].moved[1].map(s => s[2])
					}
					game.addVideo('initSkill', player, { skills, me: player === game.me })
					if (player === game.me) {
						game.addVideo('closeDialog')
					}
					game.broadcastAll((player, skills) => {
						if (player === game.me) {
							let str = ''
							skills.forEach(s => str += get.translation(s) + ' ')
							player.node.rightskillList.innerHTML = str
						}
					}, player, skills)
					lib.playerSkillOL[player.playerid] = skills
				}
				//选形象
				const playerAvatarMap = {}
				game.players.forEach(p => playerAvatarMap[p.playerid] = lib.playerCharacterOL[p.playerid])

				const avatarList = [];
				game.players.forEach(player => {
					const list = playerAvatarMap[player.playerid]
					avatarList.push([player, [
						`<span style="color:red;font-weight:700;">你可以选择一个武将作为你本局的形象</span><br>
                        <span class="tempName" style="color:orange;font-weight:700;text-align:center;font-size:20px;border-radius: 5px;">还可以在下方输入框写一个名字作为本局形象名字</span><br>
                        <input maxlength="8"  style="width:45%;text-align: center;font-size: 20px;font-weight: 700;border-radius: 5px;" value="${player.nickname || get.translation(player.name1)}">`, [list, 'characterx']], 1, false])
				})//
				var result = await game.me.chooseButtonOL(avatarList, (player, result) => {
					const input = _status.event.dialog.querySelector('input')
					if (input) {
						result.tempName = input.value
					}
					if (!result.bool) return;
					if (player === game.me) {
						const character = result.links[0]
						if (character) player.node.avatar.setBackground(character, 'character')
						// player.sex = lib.character[character][0]
					}
				}).forResult()
				for (const i in result) {
					const bool = result[i]
					if (bool.tempName) {
						game.addVideo('flashName', lib.playerOL[i], {
							avatar: lib.playerOL[i].name,
							tempName: bool.tempName
						})
						game.broadcastAll((player, tempName) => {
							player.tempName = tempName
							player.node.name.innerHTML = tempName
						}, lib.playerOL[i], bool.tempName)
					}
					if (!bool.bool) continue
					game.broadcastAll((player, avatar, skills, tempName) => {
						const nickname = tempName || player.nickname || player.node.name1.innerText
						const id = nickname + player.playerid

						player.node.name.innerHTML = nickname
						player.tempName = tempName

						swTool.copyCharacter({
							character: avatar,
							hp: 4,
							skills: skills || [],
							name: id,
							translate: nickname
						})
						player.init(id)
						player.update()
					}, lib.playerOL[i], bool.links[0], lib.playerSkillOL[lib.playerOL[i].playerid], bool.tempName)
					game.addVideo('flashAvatar', lib.playerOL[i], {
						avatar: bool.links[0],
						skills: lib.playerSkillOL[lib.playerOL[i].playerid]
					})
					game.addVideo('flashName', lib.playerOL[i], {
						avatar: bool.links[0],
						tempName: bool.tempName
					})
				}

				if(lib.configOL.identity_randomSexAndGroup) {
					//随机势力和性别
					for(let i in game.players) {
						const group = lib.group.randomGet()
						const sex = ["male", "female"].randomGet()
						const player = game.players[i]
						game.broadcastAll((player, group, sex) => {
							lib.character[player.name1][0] = sex
							lib.character[player.name1][1] = group
							player.changeGroup(group)
							player.sex = sex
						}, player, group, sex)
						game.addVideo('flashGroup', player, { group })
					}
				}
				else {
					//选势力
					const select = lib.group.map(g => ['', '', `group_${g}`])
					const groupList = game.players.map(i => {
						return [i, ['你可以选择一个势力', [select, 'vcard']], 1, false]
					})
					var result = await game.me.chooseButtonOL(groupList, (player, result) => {
						if (!result.links) return
						if (player === game.me) {
							player.changeGroup(result.links[0][2].slice(6), false, false);
						}
					}).set('processAI', function () {
						return {
							bool: false,
						}
					}).forResult()
					for (const g in result) {
						if (!result[g].bool) continue
						const player = lib.playerOL[g]
						const group = result[g].links[0][2].slice(6)
						game.broadcastAll((player, group) => {
							lib.character[player.name1][1] = group
							player.changeGroup(group)
						}, player, group)
						game.addVideo('flashGroup', player, { group })
					}
				}


				game.players.forEach(p => {
					const skills = lib.playerSkillOL[p.playerid]
					lib.character[p.name1].skills = skills
					_status.playerCharacters[p.playerid] = {
						player: p,
						skills: lib.character[p.name1][3],
						name: p.tempName || (p.nickname && p.nickname.replace('※', '')) || '',
						character: p.name1,
						info: lib.character[p.name1],
						group: p.group,
						sex: p.sex
					}
					p.addSkill(skills)
					game.broadcastAll((player, skills) => {
						lib.character[player.name1][3] = skills
						let str = ''
						skills.forEach(s => str += get.translation(s) + ' ')
						player.node.rightskillList.innerHTML = str
						if (player.nickname) {
							lib.translate[player.name1] = player.tempName || player.nickname.replace('※', '')
						}
					}, p, skills)
					game.log(`${p.node.name.innerHTML}选择了`, skills)
				})
				_status.playerCharactersUse = (characters, innnerHtml, needFunction) => {
					if (!window.swTool) {
						window.swTool = {
							copyCharacter: needFunction
						}
					}
					lib.skill.playerchangeSkill = {
						trigger: { player: 'changeSkillsAfter' },
						forced: true,
						charlotte: true,
						popup: false,
						filter() { return true },
						async content(event, trigger, player) {
							let str = ''
							const skills = player.getSkills(null, false, false).filter(s => get.translation(s) !== s);
							game.addVideo('initSkill', player, { skills })
							skills.forEach(i => {
								if (i === 'playerchangeSkill') return;
								const info = get.info(i);
								if (info && !info.charlotte) {
									str += get.translation(i) + ' '
								}
							});
							if (!player.node.rightskillList) {
								player.node.rightskillList = ui.create.div('.playerskillList', str, player)
							} else {
								player.node.rightskillList.innerHTML = str
							}
						}
					}
					lib.skill.PVPaozhan = {
						trigger: { global: 'dieAfter' },
						filter() { return game.players.length === 2 && !game.PVPaozhan },
						async content(event, trigger, player) {
							var color = get.groupnature(player.group, "raw");
							if (player.isUnseen()) color = "fire";
							player.$fullscreenpop("鏖战模式", color);
							game.broadcastAll(function () {
								_status._aozhan = true;
								ui.aozhan = ui.create.div(".touchinfo.left", ui.window);
								ui.aozhan.innerHTML = "鏖战模式";
								if (ui.time3) ui.time3.style.display = "none";
								ui.aozhanInfo = ui.create.system("鏖战模式", null, true);
								lib.setPopped(
									ui.aozhanInfo,
									function () {
										var uiintro = ui.create.dialog("hidden");
										uiintro.add("鏖战模式");
										var list = [
											"当游戏中仅剩两名玩家",
											"在鏖战模式下，任何角色均不是非转化的【桃】的合法目标。【桃】可以被当做【杀】或【闪】使用或打出。",
											"进入鏖战模式后，即使之后有两名或者更多的角色出现，仍然不会取消鏖战模式。",
										];
										var intro = '<ul style="text-align:left;margin-top:0;width:450px">';
										for (var i = 0; i < list.length; i++) {
											intro += "<li>" + list[i];
										}
										intro += "</ul>";
										uiintro.add('<div class="text center">' + intro + "</div>");
										var ul = uiintro.querySelector("ul");
										if (ul) {
											ul.style.width = "180px";
										}
										uiintro.add(ui.create.div(".placeholder"));
										return uiintro;
									},
									250
								);
								game.playBackgroundMusic();
							});
							game.countPlayer(function (current) {
								current.addSkill("aozhan");
							});
						},
						forced: true,
						charlotte: true,
					}
					const style = document.createElement('style')
					style.innerHTML = innnerHtml
					document.head.appendChild(style)
					for (const s in characters) {
						const { skills, name, character, info, group, sex } = characters[s]
						skills.push('playerchangeSkill')
						lib.character[character] = info
						const thecharacter = lib.character[character]
						if (!thecharacter) continue
						thecharacter.group = group
						thecharacter.sex = sex
						thecharacter.trashBin.remove('hiddenSkill')
						thecharacter.skills = skills
						lib.translate[character] = name || get.translation(character)
					}
					const oldme = ui.create.me
					ui.create.me = () => {
						const me = oldme.call(this, ...arguments)
						for (const s in characters) {
							const player = lib.playerOL[s]
							// const {skills,name} = characters[s]
							const { skills } = characters[s]
							let str = ''
							skills.forEach(s => {
								if (s === 'playerchangeSkill') return;
								str += get.translation(s) + ' '
							})
							if (!player.node.rightskillList) player.node.rightskillList = ui.create.div('.playerskillList', player)
							player.node.rightskillList.innerHTML = str
							// if(name) player.node.name.innerHTML = name
							const { x } = player.getBoundingClientRect()
							if (ui.window.clientWidth - x < 200) {
								player.classList.add('rightPlayer')
							} else if (x > 0 && x < 400) {
								player.classList.add('leftPlayer')
							}
						}
						ui.create.me = oldme
						return me
					}
				}
				const nei = game.players.some(p => p.identity === 'nei')
				game.broadcastAll((time, nei) => {
					if (nei) {
						game.zhu.maxHp++
						game.zhu.hp++
						game.zhu.update()
					}
					lib.configOL.choose_timeout = time
					setTimeout(function () {
						ui.arena.classList.remove("choose-character");
					}, 500);
					lib.skill.playerchangeSkill = {
						trigger: { player: 'changeSkillsAfter' },
						forced: true,
						charlotte: true,
						popup: false,
						filter() { return true },
						async content(event, trigger, player) {
							let str = ''
							const skills = player.getSkills(null, false, false).filter(s => get.translation(s) !== s);;
							skills.forEach(i => {
								if (i === 'playerchangeSkill') return;
								const info = get.info(i);
								if (info && !info.charlotte) {
									str += get.translation(i) + ' '
								}
							});
							if (!player.node.rightskillList) {
								player.node.rightskillList = ui.create.div('.playerskillList', player)
							}
							game.broadcastAll((player, str) => {
								player.node.rightskillList.innerHTML = str
							}, player, str)
						}
					}
					lib.skill.PVPaozhan = {
						trigger: { global: 'dieAfter' },
						filter() { return game.players.length === 2 && !game.PVPaozhan },
						async content(event, trigger, player) {
							game.PVPaozhan = true
							var color = get.groupnature(player.group, "raw");
							if (player.isUnseen()) color = "fire";
							player.$fullscreenpop("鏖战模式", color);
							game.broadcastAll(function () {
								_status._aozhan = true;
								ui.aozhan = ui.create.div(".touchinfo.left", ui.window);
								ui.aozhan.innerHTML = "鏖战模式";
								if (ui.time3) ui.time3.style.display = "none";
								ui.aozhanInfo = ui.create.system("鏖战模式", null, true);
								lib.setPopped(
									ui.aozhanInfo,
									function () {
										var uiintro = ui.create.dialog("hidden");
										uiintro.add("鏖战模式");
										var list = [
											"当游戏中仅剩两名玩家",
											"在鏖战模式下，任何角色均不是非转化的【桃】的合法目标。【桃】可以被当做【杀】或【闪】使用或打出。",
											"进入鏖战模式后，即使之后有两名或者更多的角色出现，仍然不会取消鏖战模式。",
										];
										var intro = '<ul style="text-align:left;margin-top:0;width:450px">';
										for (var i = 0; i < list.length; i++) {
											intro += "<li>" + list[i];
										}
										intro += "</ul>";
										uiintro.add('<div class="text center">' + intro + "</div>");
										var ul = uiintro.querySelector("ul");
										if (ul) {
											ul.style.width = "180px";
										}
										uiintro.add(ui.create.div(".placeholder"));
										return uiintro;
									},
									250
								);
								game.playBackgroundMusic();
							});
							game.countPlayer(function (current) {
								current.addSkill("aozhan");
							});
						},
						forced: true,
						charlotte: true,
					}
				}, event.chooseTime, nei)
				// game.addGlobalSkill('PVPaozhan')
				// game.players.forEach(p => p.addSkill('playerchangeSkill'))
				game.addGlobalSkill('playerchangeSkill')
				_status.videoInited = false
			})
		}
		game.chooseCharacterFreeChoiceIdentityOL = function () {
			const next = game.createEvent('chooseCharacter');
			next.setContent(function () {
				"step 0"
				game.broadcastAll(() => { ui.arena.classList.add('choose-character') })
				_status.playerNameMap = {};
				if(lib.configOL.identity_hideNickname) {
					for (let pl of game.players) {
						if(pl.nickname) _status.playerNameMap[pl.playerid] = pl.nickname || "";
					}
					game.broadcastAll(function (targets) {
						for (let player of targets) {
							if(!player.nickname) continue;
							player.nickname = `<span style="font-size: 10px;">Ciallo～(∠・ω< )⌒★</span>`;
							player.node.nameol.innerHTML = player.nickname;
						}
					}, game.players);
				}
				var i;
				var identityList;
				if (_status.mode == 'zhong') {
					event.zhongmode = true;
					identityList = ['zhu', 'zhong', 'mingzhong', 'nei', 'fan', 'fan', 'fan', 'fan'];
				} else {
					identityList = get.identityList(game.players.length);
					if (lib.configOL.double_nei) {
						switch (lib.configOL.number) {
							case 8:
								identityList.remove('fan');
								identityList.push('nei');
								break;
							case 7:
								identityList.remove('zhong');
								identityList.push('nei');
								break;
							case 6:
								identityList.remove('fan');
								identityList.push('nei');
								break;
							case 5:
								identityList.remove('fan');
								identityList.push('nei');
								break;
							case 4:
								identityList.remove('zhong');
								identityList.push('nei');
								break;
							case 3:
								identityList.remove('fan');
								identityList.push('nei');
								break;
						}
					}
				}
				//身份自选开始
				//identityList.randomSort();
				event.identityList = identityList
				"step 1"
				var uniqueIdentityList = event.identityList.slice().unique();
				//排一下顺序
				uniqueIdentityList.sort((a, b) => {
					function getPriority(identity) {
						if (identity === "zhu") return 0;
						if (identity === "zhong") return 1;
						if (identity === "fan") return 2;
						if (identity === "nei") return 3;
						return 999; //其他身份排最后
					}

					return getPriority(a) - getPriority(b);
				});

				var list = []
				for (let i = 0; i < game.players.length; i++) {
					list.push([game.players[i],
					[
						'###自选身份：请选择你倾向于做的身份（1-2个）###<div class="text center">系统将根据所有人的倾向进行分配<br>先选择的倾向度高<br>或者点击“取消”不做倾向</div>',
						[
							uniqueIdentityList,
							function (item, type, position, noclick, node) {
								node = ui.create.identityCard(item, position, noclick);
								node.link = item;
								return node;
							},
						]
					],
						[1, 2],
						false
					]);
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (player == game.me) {
						player.setIdentity(result.links[0]);
						player.node.identity.classList.remove('guessing');
						//player.changeGroup(result.links[0][2].slice(6), false, false);
					}
				}).set('switchToAuto', function () {
					_status.event.result = 'ai';
				}).set('processAI', function () {
					return {
						bool: false,
						//links: [_status.event.dialog.buttons.randomGet().link],
					}
				});
				"step 2"
				var mp = { }
				var mp2 = { "none": [], }
				for (let v of event.identityList) {
					mp[v] = []
					mp2[v] = []
				}

				for (const i in result) {
					if (result[i].bool) {
						mp[result[i].links[0]].push(i)
						if (result[i].links.length == 2) mp2[result[i].links[1]].push(i)
					}
					else {
						mp2.none.push(i)
					}
				}

				//for (const i in mp) {
				//	mp[i].randomSort()//随机排序一下，咦？
				//}

				const identityResult = {};
				var lastIdentity = []//等待被调剂的身份
				var lastIdentity2 = []//等待被调剂2的身份

				for (const identity of event.identityList) {
					//找优先倾向
					if (mp[identity].length) {
						identityResult[mp[identity].randomRemove()] = identity
					}
					//else {
					//	if (mp.none.length) identityResult[mp.none.randomRemove()] = identity
					//	else lastIdentity.push(identity)
					//}
					else lastIdentity.push(identity)
				}
				for (const key in mp2) {
					if (Array.isArray(mp2[key])) {
						mp2[key] = mp2[key].filter(item => !identityResult[item]);//只保留还没有确认身份的，滑档第二志愿
					}
				}

				for (const identity of lastIdentity) {
					//找优先倾向
					if (mp2[identity].length) {
						identityResult[mp2[identity].randomRemove()] = identity
					}
					else {
						if (mp2.none.length) identityResult[mp2.none.randomRemove()] = identity
						else lastIdentity2.push(identity)
					}
				}

				for (const i in lib.playerOL) {//看看有没有志愿都滑档的人
					if (!identityResult[i]) identityResult[i] = lastIdentity2.randomRemove()//随机调剂身份志愿
				}

				for (const i in identityResult) {
					lib.playerOL[i].identity = identityResult[i];
					lib.playerOL[i].setIdentity('cai');
					lib.playerOL[i].node.identity.classList.add('guessing');
					if (identityResult[i] == 'zhu') {
						game.zhu = lib.playerOL[i];
					}
					lib.playerOL[i].identityShown = false;
				}
				//身份自选结束
				"step 3"
				if(lib.configOL.identity_hideNickname) {
					game.broadcastAll(
						function (map) {
							for (const key in map) {
								const player = lib.playerOL[key];
								if (map[key] && player) {
									player.nickname = map[key];
									player.setNickname();
								}
							}
						},
						_status.playerNameMap
					);
				}
				game.zhu.setIdentity();
				game.zhu.identityShown = true;
				game.zhu.isZhu = (game.zhu.identity == 'zhu');
				game.zhu.node.identity.classList.remove('guessing');
				game.me.setIdentity();
				game.me.node.identity.classList.remove('guessing');
				if (game.me.special_identity) {
					game.me.node.identity.firstChild.innerHTML = get.translation(game.me.special_identity + '_bg');
				}

				for (var i = 0; i < game.players.length; i++) {
					game.players[i].send(function (zhu, zhuid, me, identity) {
						for (var i in lib.playerOL) {
							lib.playerOL[i].setIdentity('cai');
							lib.playerOL[i].node.identity.classList.add('guessing');
						}
						zhu.identityShown = true;
						zhu.identity = zhuid;
						if (zhuid == 'zhu') zhu.isZhu = true;
						zhu.setIdentity();
						zhu.node.identity.classList.remove('guessing');
						me.setIdentity(identity);
						me.identity = identity;
						me.node.identity.classList.remove('guessing');
						if (me.special_identity) {
							me.node.identity.firstChild.innerHTML = get.translation(me.special_identity + '_bg');
						}
						ui.arena.classList.add('choose-character');
					}, game.zhu, game.zhu.identity, game.players[i], game.players[i].identity);
				}
				//身份自选开始2
				"step 4"
				event.videoId = lib.status.videoId++;
				game.broadcastAll((id) => {
					var dialog = ui.create.dialog(`你的身份是：<br>`, "forcebutton");
					dialog.videoId = id;
					ui.create.spinningIdentityCard(game.me.identity, dialog);
				}, event.videoId)

				game.delay(4)

				"step 5"
				game.broadcastAll("closeDialog", event.videoId)
				//身份自选结束2
				var list;
				var list2 = [];
				var list3 = [];
				var list4 = [];
				event.list = [];
				event.list2 = [];

				var libCharacter = {};
				for (var i = 0; i < lib.configOL.characterPack.length; i++) {
					var pack = lib.characterPack[lib.configOL.characterPack[i]];
					for (var j in pack) {
						//if (j == 'zuoci') continue;
						if (lib.character[j]) libCharacter[j] = pack[j];
					}
				}
				for (i in lib.characterReplace) {
					var ix = lib.characterReplace[i];
					for (var j = 0; j < ix.length; j++) {
						if (!libCharacter[ix[j]] || lib.filter.characterDisabled(ix[j])) ix.splice(j--, 1);
					}
					if (ix.length) {
						event.list.push(i);
						event.list2.push(i);
						list4.addArray(ix);
						var bool = false;
						for (var j of ix) {
							if (libCharacter[j][4] && libCharacter[j][4].includes('zhu')) {
								bool = true; break;
							}
						}
						(bool ? list2 : list3).push(i);
					}
				}
				game.broadcast(function (list) {
					for (var i in lib.characterReplace) {
						var ix = lib.characterReplace[i];
						for (var j = 0; j < ix.length; j++) {
							if (!list.includes(ix[j])) ix.splice(j--, 1);
						}
					}
					_status.characterlist = list
				}, list4);
				for (i in libCharacter) {
					if (list4.includes(i)) continue;
					if (lib.filter.characterDisabled(i, libCharacter)) continue;
					event.list.push(i);
					event.list2.push(i);
					list4.push(i);
					if (libCharacter[i][4] && libCharacter[i][4].includes('zhu')) {
						list2.push(i);
					}
					else {
						list3.push(i);
					}
				}
				_status.characterlist = list4.slice(0);

				event.useTime = lib.configOL.choose_timeout
				event.chooseTime = lib.configOL.chooseCharacter_moreTime
				game.broadcastAll((num) => {
					lib.configOL.choose_timeout = Number(num)
				}, event.chooseTime)

				//自由点将开始1
				if (lib.configOL.identity_listNum == 'dianjiang') {
					game.broadcastAll(function (list, id, zhu) {
						_status.characterlist = list;
						if (game.me == zhu) {
							var dialog = ui.create.characterDialog('heightset').open()
							dialog.id = id
						}
					}, _status.characterlist, event.videoId, game.zhu);

					game.zhu.chooseButton(true)
						.set('selectButton', (lib.configOL.double_character ? 2 : 1)).set('dialog', event.videoId)
				}
				//自由点将结束1
				else {
					if (lib.configOL.identity_listNum == 'normal') {
						let finalNum = lib.configOL.choice_zhu;
						if (lib.configOL.unbalanced_mode) finalNum = 12;
						var getZhuList = function (list2) {
							var limit_zhu = lib.configOL.limit_zhu;
							if (!limit_zhu || limit_zhu == 'off') return list2.slice(0).sort(lib.sort.character);
							if (limit_zhu != 'group') {
								var num = (parseInt(limit_zhu) || 6);
								return list2.randomGets(num).sort(lib.sort.character);
							}
							var getGroup = function (name) {
								if (lib.characterReplace[name]) return lib.character[lib.characterReplace[name][0]][1];
								return lib.character[name][1];
							}
							var list2x = list2.slice(0);
							list2x.randomSort();
							for (var i = 0; i < list2x.length; i++) {
								for (var j = i + 1; j < list2x.length; j++) {
									if (getGroup(list2x[i]) == getGroup(list2x[j])) {
										list2x.splice(j--, 1);
									}
								}
							}
							list2x.sort(lib.sort.character);
							return list2x;
						}
						list = getZhuList(list2).concat(list3.randomGets(finalNum));
					}
					else {
						let finalNum = swTool.getSelect() || 6
						if (lib.configOL.unbalanced_mode) finalNum = 12;
						var getZhuList = function (list2) {
							var limit_zhu = lib.configOL.limit_zhu;
							if (!limit_zhu || limit_zhu == 'off') return list2.slice(0).sort(lib.sort.character);
							if (limit_zhu != 'group') {
								var num = (parseInt(limit_zhu) || 6);
								return list2.randomGets(num).sort(lib.sort.character);
							}
							var getGroup = function (name) {
								if (lib.characterReplace[name]) return lib.character[lib.characterReplace[name][0]][1];
								return lib.character[name][1];
							}
							var list2x = list2.slice(0);
							list2x.randomSort();
							for (var i = 0; i < list2x.length; i++) {
								for (var j = i + 1; j < list2x.length; j++) {
									if (getGroup(list2x[i]) == getGroup(list2x[j])) {
										list2x.splice(j--, 1);
									}
								}
							}
							list2x.sort(lib.sort.character);
							return list2x;
						}
						list = getZhuList(list2).concat(list3.randomGets(finalNum));
					}
					if (event.zhongmode) {
						list = event.list.randomGets(8);
					}
					var next = game.zhu.chooseButton(true);
					next.set('selectButton', (lib.configOL.double_character ? 2 : 1));
					next.set('createDialog', ['选择角色', [list, 'characterx']]);
					next.set('ai', function (button) {
						return Math.random();
					});
				}

				"step 6"
				//自由点将开始2
				if (!result.links || result.links?.length == 0) {
					result.links = _status.characterlist.randomGets(lib.configOL.double_character ? 2 : 1)
				}
				if (lib.configOL.identity_listNum == 'dianjiang') {
					if (game.zhu.isOnline()) {
						game.zhu.send("closeDialog", event.id)
					}
					else if (game.zhu == game.me) {
						var dialog = get.idDialog(event.id);
						if (dialog) {
							dialog.close();
						}
					}
				}
				//自由点将结束2
				if (!game.zhu.name) {
					game.zhu.init(result.links[0], result.links[1])
				}
				event.list.remove(get.sourceCharacter(game.zhu.name1));
				event.list.remove(get.sourceCharacter(game.zhu.name2));
				event.list2.remove(get.sourceCharacter(game.zhu.name1));
				event.list2.remove(get.sourceCharacter(game.zhu.name2));

				if (game.players.length > 4) {
					if (!game.zhu.isInitFilter('noZhuHp')) {
						game.zhu.maxHp++;
						game.zhu.hp++;
						game.zhu.update();
					}
				}
				game.broadcast(function (zhu, name, name2, addMaxHp) {
					if (!zhu.name) {
						zhu.init(name, name2);
					}
					if (addMaxHp && !zhu.isInitFilter("noZhuHp")) {
						zhu.maxHp++;
						zhu.hp++;
						zhu.update();
					}
				}, game.zhu, result.links[0], result.links[1], game.players.length > 4);

				if (game.zhu.group == 'shen' || game.zhu.group == "western" && !game.zhu.isUnseen(0)) {
					game.zhu._groupChosen = "kami";
					var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key', 'shen'];
					for (var i = 0; i < list.length; i++) {
						if (!lib.group.includes(list[i])) list.splice(i--, 1);
						else list[i] = ['', '', 'group_' + list[i]];
					}
					game.zhu.chooseButton(['请选择你的势力', [list, 'vcard']], true).set('ai', function () {
						return Math.random();
					});
				}
				else if (get.is.double(game.zhu.name1)) {
					game.zhu._groupChosen = true;
					var list = get.is.double(game.zhu.name1, true);
					for (var i = 0; i < list.length; i++) {
						if (!lib.group.includes(list[i])) list.splice(i--, 1);
						else list[i] = ['', '', 'group_' + list[i]];
					}
					game.zhu.chooseButton(['请选择你的势力', [list, 'vcard']], true).set('ai', function () {
						return Math.random();
					});
				}
				else event.goto(8);
				"step 7"
				var name = result.links[0][2].slice(6);
				game.zhu.changeGroup(name);
				"step 8"
				var list = [];
				var selectButton = (lib.configOL.double_character ? 2 : 1);
				var num = Math.floor(event.list.length / (game.players.length - 1));
				//自由点将开始3
				if (lib.configOL.identity_listNum == 'dianjiang') {
					game.broadcastAll(function (id, zhu) {
						if (game.me != zhu) {
							var dialog = ui.create.characterDialog('heightset').open()
							dialog.id = id
						}
					}, event.videoId, game.zhu);
				}
				//自由点将结束3
				for (let i = 0; i < game.players.length; i++) {
					swTool.onlineSelectNum = swTool.getSelect()
					if (game.players[i] != game.zhu) {
						//自由点将开始4
						if (lib.configOL.identity_listNum == 'dianjiang') {
							list.push([game.players[i],
							event.videoId, selectButton, true
							]);
						}//自由点将结束4
						else {
							const identity = game.players[i].identity;
							let num2;
							if (event.zhongmode) {
								if (identity == "nei" || identity == "zhu") num2 = 8;
								else num2 = 6;
							} else {
								num2 = lib.configOL["choice_" + identity];
							}
							let str = "选择角色";
							if (game.players[i].special_identity) {
								str += "（" + get.translation(game.players[i].special_identity) + "）";
							}
							if (lib.configOL.identity_listNum != 'normal' && swTool.onlineSelectNum) {
								list.push([game.players[i],
								[str, [event.list.randomRemove(swTool.onlineSelectNum), 'characterx']], selectButton, true
								]);
							} else {
								//TODO:此处要因身份而异
								list.push([game.players[i],
								[str, [event.list.randomRemove(num2), 'characterx']], selectButton, true
								]);
							}
						}
					}
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (game.online || player == game.me) player.init(result.links[0], result.links[1]);
				}).set("switchToAuto", function () {
					_status.event.result = "ai";
				})
					.set("processAI", function () {
						return "ai";
					});


				"step 9"
				game.broadcastAll((num) => {
					lib.configOL.choose_timeout = Number(num)
				}, event.useTime)
				//自由点将开始5
				if (lib.configOL.identity_listNum == 'dianjiang') game.broadcastAll("closeDialog", event.id)
				//自由点将结束5
				var shen = [];
				for (var i in result) {
					if (result[i] && result[i].links) {
						for (var j = 0; j < result[i].links.length; j++) {
							event.list2.remove(get.sourceCharacter(result[i].links[j]));
						}
					}
				}

				for (var i in result) {
					if (result[i] == 'ai') {
						result[i] = event.list2.randomRemove(lib.configOL.double_character ? 2 : 1);
						for (var j = 0; j < result[i].length; j++) {
							var listx = lib.characterReplace[result[i][j]];
							if (listx && listx.length) result[i][j] = listx.randomGet();
						}
					}
					else {
						result[i] = result[i].links;
					}
					if (get.is.double(result[i][0]) || (lib.character[result[i][0]] && (lib.character[result[i][0]].group == "shen" || lib.character[result[i][0]].group == "western") && !lib.character[result[i][0]].hasHiddenSkill)) shen.push(lib.playerOL[i]);
				}
				event.result2 = result;
				if (shen.length) {
					var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key'];
					for (var i = 0; i < list.length; i++) {
						if (!lib.group.includes(list[i])) list.splice(i--, 1);
						else list[i] = ['', '', 'group_' + list[i]];
					}
					for (var i = 0; i < shen.length; i++) {
						if (get.is.double(result[shen[i].playerid][0])) {
							shen[i]._groupChosen = "double";
							shen[i] = [
								shen[i],
								[
									"请选择你的势力",
									[
										get.is.double(result[shen[i].playerid][0], true).map(function (i) {
											return ["", "", "group_" + i];
										}),
										"vcard",
									],
								],
								1,
								true,
							];
						} else {
							shen[i]._groupChosen = "kami";
							shen[i] = [shen[i], ["请选择你的势力", [list, "vcard"]], 1, true];
						}
					}
					game.me.chooseButtonOL(shen, function (player, result) {
						if (player == game.me) player.changeGroup(result.links[0][2].slice(6), false, false);
					}).set('switchToAuto', function () {
						_status.event.result = 'ai';
					}).set('processAI', function () {
						return {
							bool: true,
							links: [_status.event.dialog.buttons.randomGet().link],
						}
					});
				}
				else event._result = {};
				"step 10"
				if (!result) result = {};
				for (var i in result) {
					if (result[i] && result[i].links) result[i] = result[i].links[0][2].slice(6);
					else if (result[i] == 'ai') result[i] = function () {
						var player = lib.playerOL[i];
						var list = ['wei', 'shu', 'wu', 'qun', 'jin', 'key'];
						for (var ix = 0; ix < list.length; ix++) {
							if (!lib.group.includes(list[ix])) list.splice(ix--, 1);
						}
						if (_status.mode != 'zhong' && game.zhu && game.zhu.group) {
							if (['re_zhangjiao', 'liubei', 're_liubei', 'caocao', 're_caocao', 'sunquan', 're_sunquan', 'zhangjiao', 'sp_zhangjiao', 'caopi', 're_caopi', 'liuchen', 'caorui', 'sunliang', 'sunxiu', 'sunce', 're_sunben', 'ol_liushan', 're_liushan', 'key_akane', 'dongzhuo', 're_dongzhuo', 'ol_dongzhuo', 'jin_simashi', 'caomao'].includes(game.zhu.name)) return game.zhu.group;
							if (game.zhu.name == 'yl_yuanshu') {
								if (player.identity == 'zhong') list.remove('qun');
								else return 'qun';
							}
							if (['sunhao', 'xin_yuanshao', 're_yuanshao', 're_sunce', 'ol_yuanshao', 'yuanshu', 'jin_simazhao', 'liubian'].includes(game.zhu.name)) {
								if (player.identity != 'zhong') list.remove(game.zhu.group);
								else return game.zhu.group;
							}
						}
						return list.randomGet();
					}();
				}
				var result2 = event.result2;
				game.broadcast(function (result, result2) {
					for (var i in result) {
						if (!lib.playerOL[i].name) {
							lib.playerOL[i].init(result[i][0], result[i][1]);
						}
						if (result2[i] && result2[i].length) lib.playerOL[i].changeGroup(result2[i], false, false);
					}
					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				}, result2, result);

				for (var i in result2) {
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result2[i][0], result2[i][1]);
					}
					if (result[i] && result[i].length) lib.playerOL[i].changeGroup(result[i], false, false);
				}

				if (event.special_identity) {
					for (var i in event.special_identity) {
						game.zhu.addSkill(i);
					}
				}
				for (var i = 0; i < game.players.length; i++) {
					_status.characterlist.remove(game.players[i].name);
					_status.characterlist.remove(game.players[i].name1);
					_status.characterlist.remove(game.players[i].name2);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			});
		}
    }
}
